package com.jie.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class IPUtils {
    private static final String X_FORWARDED_FOR = "x-forwarded-for";

    private static final String UNKNOWN = "unknown";

    private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";

    public static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    public static final String HTTP_CLIENT_IP = "HTTP_CLIENT_IP";

    public static final String HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";

    public static final String X_REAL_IP = "X-Real-IP";
    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader(X_FORWARDED_FOR);
        if (StrUtil.isNotBlank(ip)) {
            log.info("ip:{}", ip);
        }
        if (StrUtil.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }

        if (StrUtil.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            if (getIp(request, PROXY_CLIENT_IP)) {
                return ip;
            }

            if (getIp(request, WL_PROXY_CLIENT_IP)) {
                return ip;
            }

            if (getIp(request, HTTP_CLIENT_IP)) {
                return ip;
            }

            if (getIp(request, HTTP_X_FORWARDED_FOR)) {
                return ip;
            }

            if (getIp(request, X_REAL_IP)) {
                return ip;
            }

            return request.getRemoteAddr();
        }

        return ip;
    }
        private static boolean getIp(HttpServletRequest request, String headString) {
            String ip = request.getHeader(headString);
            return StrUtil.isNotBlank(ip);
    }
}
